var express = require('express');
const jwt = require("jsonwebtoken");
const { secretKey } = require('../utils/salt');
var router = express.Router();
var {reg,login,isUse,generatorToken} = require("../service/userService.js");
/* GET users listing. */
// 注册
router.post('/reg', async function(req, res, next) {
  const { name, email, phone,repeatPwd,status,power} = req.body;
  const data = await reg({  name, email, phone,repeatPwd,status,power});
  res.send(data);
});

// 登录
router.get('/login', async function(req, res, next) {
const data = await login( req.query);
const result = {
  status:false
};
if (data.length) {

  result.status = true;
  let roles;
  if (data[0].power==0) {
    roles= ['super-admin']
  }else if(data[0].power==1){
    roles= ['supplier']
  }else{
    roles= ['store']
  }
  result.token = generatorToken({roles,name:data[0].name,_id:data[0]._id});

  
}
res.send(result);
});
router.get('/getInfo', async function(req, res, next) {
  let {token}=req.query
  await jwt.verify(token,secretKey,(error,decodeed)=>{
    if (error) {
      console.log(error,1);
      return
    }
     res.send(decodeed)
  })
});

// 验证用户名
router.post('/isUse', async function(req, res, next) {
   const  status = await isUse( req.body);
  res.send(
    status
  );
});
module.exports = router;
